﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.Procurements;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Write.API.Applicantions.Command.ProcurementsCommand;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler.ProcurementsCommandCommand
{
    public class UpdStateHandler : IRequestHandler<UpdStateCommand, APIResult<object>>
    {
        /// <summary>
        /// 仓储
        /// </summary>
        private readonly IBaseRepository<PurchaseInvoice> _purchaseInvoice;
        //private readonly IMapper mapper;
        private readonly ILogger<UpdStateHandler> logger;

        public UpdStateHandler(IBaseRepository<PurchaseInvoice> purchaseInvoice, ILogger<UpdStateHandler> logger)
        {
            _purchaseInvoice = purchaseInvoice;
            this.logger = logger;
            //this.mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(UpdStateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result=new APIResult<object>();
            try
            {
                result.Code = APIEnum.修改成功;
                result.Msg = APIEnum.修改成功.ToString();
                var invoice = _purchaseInvoice.GetAll().Result.Where(x => x.Peid == request.Peid).FirstOrDefault();
                if (invoice == null)
                {
                    result.Code = APIEnum.操作成功;
                    result.Msg = "未找到对应的采购发票";
                    return result;
                }
                invoice.DocumentStuct = false;
                await _purchaseInvoice.Update(invoice);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "处理请求时发生错误");
                throw;
            }
            return await Task.FromResult(result);
        }
    }
}
